package com.shuwen.gcdj.service.statistic;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.util.CollectionUtils;
import com.shuwen.gcdj.bean.conditionMonitoring.request.*;
import com.shuwen.gcdj.bean.conditionMonitoring.response.*;
import com.shuwen.gcdj.bean.sysDictionary.request.SysDictionaryReq;
import com.shuwen.gcdj.bean.sysDictionary.response.StartEndTImeResp;
import com.shuwen.gcdj.bean.sysDictionary.response.SysDictionaryResp;
import com.shuwen.gcdj.common.api.CommonResult;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.util.BeanHelper;
import com.shuwen.gcdj.common.util.FieldUtil;
import com.shuwen.gcdj.mapper.mysql.Statistic.StatisticsHealthMapper;
import com.shuwen.gcdj.mapper.mysql.Statistic.StatisticsMechanismvibrationMapper;
import com.shuwen.gcdj.mapper.mysql.Statistic.StatisticsSensorMapper;
import com.shuwen.gcdj.mapper.mysql.Statistic.StatisticsTrendstabilityMapper;
import com.shuwen.gcdj.mapper.mysql.sysDictionary.SysDictionaryMapper;
import com.shuwen.gcdj.mapper.tdengine.Statistic.StatisticStressMetersMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 状态监控中心
 *
 * @author XYC
 */
@Service
@AllArgsConstructor
@Slf4j
public class ConditionMonitoringService {

    private final SysDictionaryMapper sysDictionaryMapper;

    private final StatisticsSensorMapper statisticsSensorMapper;

    private final StatisticStressMetersMapper statisticStressMetersMapper;

    private final StatisticsTrendstabilityMapper statisticsTrendstabilityMapper;

    private final StatisticsMechanismvibrationMapper statisticsMechanismvibrationMapper;

    private final StatisticsHealthMapper statisticsHealthMapper;

    @Autowired
    private final HomeService homeService;

    /**
     * 查询主梁监测位置
     *
     * @return
     */
    public CommonResult<List<MonitoringPositionResp>> getMonitoringPosition(StatisticMonitoringCriteriaReq req) {
        if (StringUtils.isEmpty(req.getEquipmentCode())) {
            return CommonResult.failed("设备不存在");
        }
        //查询设备对象
        SysDictionaryReq equipment = new SysDictionaryReq();
        equipment.setParentCode(Constants.CRANE_EQUIPMENT_OBJECT);
        equipment.setCode(req.getEquipmentCode());
        equipment.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        SysDictionaryResp equipmentObject = sysDictionaryMapper.getSingle(equipment);
        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
        dictionaryReq.setParentCode(Constants.BASICS_SENSOR_MAIN_BEAM_POSITION);
        dictionaryReq.setOperateObject(equipmentObject.getCode());
        dictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> data = sysDictionaryMapper.getList(dictionaryReq);
        switch (req.getPositionType()) {
            case Constants.MAIN_BEAM_VALUE:
                data = data.stream().filter(dictionary -> dictionary.getCode().equals(Constants.MAIN_BEAM)).collect(Collectors.toList());
                break;
            case Constants.MAIN_STRUCTURE_VALUE:
                data = data.stream().filter(dictionary -> dictionary.getCode().equals(Constants.MAIN_STRUCTURE)).collect(Collectors.toList());
                break;
        }
        return CommonResult.success(BeanHelper.copyList(data, MonitoringPositionResp.class));
    }

    /**
     * 查询主结构监测位置
     *
     * @return
     */
    public List<MonitoringPositionResp> getMainStructurePosition() {
        SysDictionaryReq req = new SysDictionaryReq();
        req.setParentCode(Constants.BASICS_SENSOR_MAIN_BEAM_POSITION);
        req.setCode(Constants.MAIN_STRUCTURE);
        List<SysDictionaryResp> data = sysDictionaryMapper.getList(req);
        return BeanHelper.copyList(data, MonitoringPositionResp.class);
    }

    /**
     * 主梁
     *
     * @param req
     * @return
     */
    public CommonResult<List<StatisticMonitoringBeamResp>> getMainBeamAsync(StatisticMonitoringCriteriaReq req) {
        if (StringUtils.isEmpty(req.getEquipmentCode())) {
            return CommonResult.failed("设备不存在");
        }
        List<StatisticMonitoringBeamResp> statisticMonitoringBeamResps = new ArrayList<>();
        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
        //判断日期是否为空没有就获取当前日期
        req.setTs(req.getTs() == null ? LocalDateTime.now() : req.getTs());
        //查询设备对象
        SysDictionaryReq equipment = new SysDictionaryReq();
        equipment.setParentCode(Constants.CRANE_EQUIPMENT_OBJECT);
        equipment.setCode(req.getEquipmentCode());
        equipment.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        SysDictionaryResp equipmentObject = sysDictionaryMapper.getSingle(equipment);
        if (equipmentObject == null) {
            return CommonResult.success(statisticMonitoringBeamResps);
        }
        //查询主梁所有位置
        dictionaryReq.setParentCode(Constants.BASICS_SENSOR_MAIN_BEAM_POSITION);
        dictionaryReq.setOperateObject(equipmentObject.getCode());
        dictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> positionData = sysDictionaryMapper.getList(dictionaryReq).stream()
                .filter(dictionary -> dictionary.getCode().equals(Constants.MAIN_BEAM)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(positionData)) {
            return CommonResult.success(statisticMonitoringBeamResps);
        }
        //首页状态中心传感器查询数量与间隔
        StartEndTImeResp valueRange;
        if (req.getTimeInterval() != null) {
            valueRange = timeRange(req.getTs(), req.getTimeInterval());
        } else {
            valueRange = sensorStatistics(req.getTs(), Constants.MAIN_BEAM1);
        }
        //位置value
        List<Integer> positions = !CollectionUtils.isEmpty(req.getPosition()) ? req.getPosition() :
                positionData.stream().map(SysDictionaryResp::getValue).collect(Collectors.toList());
        //获取相关位置的传感器
        List<StatisticsSensorResp> senSerDatas = statisticsSensorMapper.getList(positions, req.getEquipmentCode());
        //超级表
        SysDictionaryReq superTableReq = new SysDictionaryReq();
        superTableReq.setParentCode(Constants.EQUIPMENT_CODE_TDSTABLE);
        superTableReq.setOperateObject(req.getEquipmentCode());
        superTableReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> superTables = sysDictionaryMapper.getList(superTableReq);
        //plc超级表数据
        SysDictionaryResp superTable = superTables.stream().filter(x -> x.getCode().contains(Constants.GANTRY_CRANE_STRAIN)).findFirst().orElse(new SysDictionaryResp());
        return CommonResult.success(resultData(req, senSerDatas, positionData,valueRange, superTable));
    }

    //数据处理(应变)
    public List<StatisticMonitoringBeamResp> resultData(StatisticMonitoringCriteriaReq req,
                                                        List<StatisticsSensorResp> senSerDatas, List<SysDictionaryResp> positionData
            , StartEndTImeResp valueRange, SysDictionaryResp sysDictionary) {
        List<StatisticMonitoringBeamResp> statisticMonitoringBeamResps = new ArrayList<>();
        StressMetersReq meteReq = new StressMetersReq();
        if (CollectionUtils.isEmpty(senSerDatas)) {
            return statisticMonitoringBeamResps;
        }
        meteReq.setLimit(valueRange.getLimit());
        meteReq.setTableName(sysDictionary.getCode());
        meteReq.setStartTime(valueRange.getStartTime());
        meteReq.setEndDateTime(valueRange.getEndDateTime());
        for (StatisticsSensorResp resp : senSerDatas) {
            meteReq.setSensorCode(resp.getSensorcode());
            meteReq.setEquipmentCode(req.getEquipmentCode());
            StatisticMonitoringBeamResp data = new StatisticMonitoringBeamResp();
            //查询主梁传感器数据
            List<TDSensorCodeDataAllResp> allResps = statisticStressMetersMapper.getStrainListA(meteReq).stream().sorted(Comparator.comparing(TDSensorCodeDataAllResp::getTs)).collect(Collectors.toList());
            //判断是否有数据返回状态
            boolean state = allResps.size() > 0;
            //位置名称
            SysDictionaryResp position = positionData.stream()
                    .filter(x -> x.getValue().equals(resp.getPosition())).findFirst().orElse(new SysDictionaryResp());
            //拿取时间
            List<String> dateTimeNames = allResps.stream().map(t -> DateUtil.format(t.getTs(), DatePattern.NORM_TIME_PATTERN)).collect(Collectors.toList());
            //拿取值
            List<String> numerics = FieldUtil.usersBlankNum(resp.getSensorcode(),TDSensorCodeDataAllResp.class,allResps);
            data.setSensorCode(resp.getSensorcode());
            data.setPosition(position.getName());
            data.setPositionValue(position.getValue());
            data.setDateTimeName(CollectionUtils.isEmpty(dateTimeNames) ? new ArrayList<>() : dateTimeNames);
            data.setNumericValue(CollectionUtils.isEmpty(numerics) ? new ArrayList<>() : numerics);
            data.setState(state);
            data.setDataColor(colorCode(resp.getSensortype()));
            data.setSensorName(resp.getRemark());
            statisticMonitoringBeamResps.add(data);
        }
        return statisticMonitoringBeamResps;
    }


    /**
     * 主结构
     *
     * @param req
     * @return
     */
    public CommonResult<List<StatisticMonitoringBeamResp>> getMainStructureAsync(StatisticMonitoringCriteriaReq req) {
        if (StringUtils.isEmpty(req.getEquipmentCode())) {
            return CommonResult.failed("设备不存在");
        }
        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
        //判断日期是否为空没有就获取当前日期
        req.setTs(req.getTs() == null ? LocalDateTime.now() : req.getTs());
        //查询倾角所有位置
        dictionaryReq.setParentCode(Constants.BASICS_SENSOR_MAIN_BEAM_POSITION);
        dictionaryReq.setCode(Constants.MAIN_STRUCTURE);
        dictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> positionData = sysDictionaryMapper.getList(dictionaryReq);
        //首页状态中心传感器查询数量与间隔
        StartEndTImeResp valueRange;
        if (req.getTimeInterval() != null) {
            valueRange = timeRange(req.getTs(), req.getTimeInterval());
        } else {
            valueRange = sensorStatistics(req.getTs(), Constants.MAIN_BEAM1);
        }
        //位置value
        List<Integer> positions = !CollectionUtils.isEmpty(req.getPosition()) ? req.getPosition() :
                positionData.stream().map(SysDictionaryResp::getValue).collect(Collectors.toList());
        //获取相关位置的传感器
        List<StatisticsSensorResp> senSerDatas = statisticsSensorMapper.getList(positions, req.getEquipmentCode());
        //获取Td超级表名
        SysDictionaryReq superTableReq = new SysDictionaryReq();
        superTableReq.setParentCode(Constants.EQUIPMENT_CODE_TDSTABLE);
        superTableReq.setOperateObject(req.getEquipmentCode());
        superTableReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> superTables = sysDictionaryMapper.getList(superTableReq);
        //plc超级表数据
        SysDictionaryResp superTable = superTables.stream().filter(x -> x.getCode().contains(Constants.GANTRY_CRANE_TILT)).findFirst().orElse(new SysDictionaryResp());

        return CommonResult.success(resultVibrationData(req, senSerDatas, positionData, valueRange, superTable));
    }


    //数据处理(倾角)
    public List<StatisticMonitoringBeamResp> resultVibrationData(StatisticMonitoringCriteriaReq req,
                                                                 List<StatisticsSensorResp> senSerDatas, List<SysDictionaryResp> positionData
            , StartEndTImeResp valueRange, SysDictionaryResp sysDictionary) {
        List<StatisticMonitoringBeamResp> statisticMonitoringBeamResps = new ArrayList<>();
        StressMetersReq meteReq = new StressMetersReq();
        if (CollectionUtils.isEmpty(senSerDatas)) {
            return statisticMonitoringBeamResps;
        }
        meteReq.setLimit(valueRange.getLimit());
        meteReq.setTableName(sysDictionary.getCode());
        meteReq.setStartTime(valueRange.getStartTime());
        meteReq.setEndDateTime(valueRange.getEndDateTime());
        for (StatisticsSensorResp resp : senSerDatas) {
            meteReq.setSensorCode(resp.getSensorcode());
            meteReq.setEquipmentCode(req.getEquipmentCode());
            StatisticMonitoringBeamResp data = new StatisticMonitoringBeamResp();
            //查询主梁传感器数据
            List<TDSensorCodeDataAllResp> datas = statisticStressMetersMapper.getTiltMetersListA(meteReq).stream().sorted(Comparator.comparing(TDSensorCodeDataAllResp::getTs)).collect(Collectors.toList());
            //判断是否有数据返回状态
            boolean state = datas.size() > 0;
            //位置名称
            SysDictionaryResp position = positionData.stream()
                    .filter(x -> x.getValue().equals(resp.getPosition())).findFirst().orElse(new SysDictionaryResp());
            //拿取时间
            List<String> dateTimeNames = datas.stream().map(t -> DateUtil.format(t.getTs(), DatePattern.NORM_TIME_PATTERN)).collect(Collectors.toList());
            //拿取值
            List<String> numerics = FieldUtil.usersBlankNum(resp.getSensorcode(),TDSensorCodeDataAllResp.class,datas);
            data.setSensorCode(resp.getSensorcode());
            data.setPosition(position.getName());
            data.setPositionValue(position.getValue());
            data.setDateTimeName(CollectionUtils.isEmpty(dateTimeNames) ? new ArrayList<>() : dateTimeNames);
            data.setNumericValue(CollectionUtils.isEmpty(numerics) ? new ArrayList<>() : numerics);
            data.setState(state);
            data.setDataColor(colorCode(resp.getSensortype()));
            data.setSensorName(resp.getRemark());
            statisticMonitoringBeamResps.add(data);
        }
        return statisticMonitoringBeamResps;
    }


    /**
     * 起升结构
     *
     * @param req
     * @return
     */
    public CommonResult<List<StatisticCenterTrendStabilityResp>> getLiftingStructureAsync(CenterTrendstabilityReq req) {
        if (StringUtils.isEmpty(req.getEquipmentCode())) {
            return CommonResult.failed("设备不存在");
        }
        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
        StrainSensorQueryReq sensorResp = new StrainSensorQueryReq();
        dictionaryReq.setParentCode(Constants.STATISTICS_TRENDSTABILITY_MONITOR_LOCATION);
        dictionaryReq.setRemark(Constants.LIFTING);
        dictionaryReq.setOperateObject(req.getEquipmentCode());
        //位置
        List<SysDictionaryResp> positionData = sysDictionaryMapper.getList(dictionaryReq);
        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.parentCode = Constants.LIFTING_HEALTH;
        List<SysDictionaryResp> health = sysDictionaryMapper.getList(sysDictionaryReq);
        List<String> healths = health.stream().map(SysDictionaryResp::getName).collect(Collectors.toList());

        //获取子表
        SysDictionaryReq dict = new SysDictionaryReq();
        dict.setParentCode(Constants.SENSOR_TABLES);
        dict.setOperateObject(req.getEquipmentCode());
        dict.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> sysDictionaries = sysDictionaryMapper.getList(dict);

        //获取设备吨位
        sysDictionaryReq.setParentCode(Constants.CRANE_EQUIPMENT_OBJECT);
        sysDictionaryReq.setCode(req.getEquipmentCode());
        sysDictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        SysDictionaryResp equipment = sysDictionaryMapper.getSingle(sysDictionaryReq);
        List<SysDictionaryResp> getSysDictionaryResp = getSysDictionaryResp(Constants.MONITOR_VIBRATION_STATUS, equipment.getCode());

        //卷筒轴健康度
        //String reelShaft = health.stream().filter(sysDictionaryResp -> sysDictionaryResp.getCode().equals(Constants.REEL_SHAFT)).findFirst().orElse(new SysDictionaryResp()).getName();
        //轴承健康度
        //String bearing = health.stream().filter(dictionaryResp -> dictionaryResp.getCode().equals(Constants.BEARING)).findFirst().orElse(new SysDictionaryResp()).getName();
        //位置value
        List<Integer> positions = positionData.stream().map(SysDictionaryResp::getValue).collect(Collectors.toList());
        sensorResp.setEquipmentCode(req.getEquipmentCode());
        sensorResp.setMonitorLocations(positions);
        sensorResp.setDateTime(req.getViewDate() != null ? req.getViewDate() : LocalDate.now());
        //查询趋势平稳度
        List<StatisticsTrendstabilityResp> trends = statisticsTrendstabilityMapper.getTimeList(sensorResp);
        //查询振动情况
        List<StatisticsMechanismVibrationResp> mechanisms = statisticsMechanismvibrationMapper.getList(req.getEquipmentCode());
        return CommonResult.success(setTrendStabilityResponse(positionData, mechanisms, trends, healths, req, getSysDictionaryResp, sysDictionaries));
    }

    //起升结构
    public List<StatisticCenterTrendStabilityResp> setTrendStabilityResponse(List<SysDictionaryResp> positionData, List<StatisticsMechanismVibrationResp> mechanisms
            , List<StatisticsTrendstabilityResp> trends, List<String> healths, CenterTrendstabilityReq req, List<SysDictionaryResp> getSysDictionaryResp,
                                                                             List<SysDictionaryResp> sysDictionaries) {
        List<StatisticCenterTrendStabilityResp> centerTrendStabilityResps = new ArrayList<>();

        // LocalDateTime dateTime = LocalDateTime.now();
        HealthQueryReq healthQueryReq = new HealthQueryReq();
        //healthQueryReq.setTime(dateTime);
        healthQueryReq.setLocation(Constants.REEL_HEALT);
        healthQueryReq.setEquipmentCode(req.getEquipmentCode());

        SysDictionaryReq statistics = new SysDictionaryReq();
        statistics.setParentCode(Constants.SENSOR_STATISTICS);
        statistics.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> datas = sysDictionaryMapper.getList(statistics);
        //首页应变传感器查询数量与间隔
        SysDictionaryResp dictionaryResp = datas.stream().filter(x -> x.getValue().equals(Constants.VIBRATION_SENSOR)).findFirst().orElse(new SysDictionaryResp());
        //获取查询时间间隔（秒）
        int number = dictionaryResp.getCode() != null ? Integer.parseInt(dictionaryResp.getCode()) : Constants.VIBRATION_TIME;
        //获取查询数量
        int limit = dictionaryResp.getName() != null ? Integer.parseInt(dictionaryResp.getName()) : Constants.NUMBER_OF_QUERIES;
        //查询开始时间
        String startDate = LocalDateTime.now().minusSeconds(number).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //查询结束时间
        String endDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //卷轴健康度
        List<HealthResp> reelHealtList = statisticsHealthMapper.getList(healthQueryReq).stream().filter(health -> health.getRemark() != null).collect(Collectors.toList());
        healthQueryReq.setLocation(Constants.BEARING_HEALT);
        //轴承健康度
        List<HealthResp> bearingHealtList = statisticsHealthMapper.getList(healthQueryReq).stream().filter(health -> health.getRemark() != null).collect(Collectors.toList());
        for (SysDictionaryResp position : positionData) {
            StatisticCenterTrendStabilityResp data = new StatisticCenterTrendStabilityResp();
            List<StatisticTrendSmoothnessResp> trendDatas = new ArrayList<>();
            //获取振动传感器code
            List<SysDictionaryResp> sysDictionaryResps = getSysDictionaryResp.stream().filter(dic -> dic.getRemark().equals(position.getRemark()+"_"+position.getValue())).collect(Collectors.toList());
            StressMetersReq meters = new StressMetersReq();
            meters.setEquipmentCode(req.getEquipmentCode());
            meters.setSensorCodeList(sysDictionaryResps.stream().map(SysDictionaryResp::getCode).collect(Collectors.toList()));
            meters.setStartTime(startDate);
            meters.setEndDateTime(endDate);
            meters.setLimit(limit);
            //查询振动传感器数据
            List<TDSensorCodeDataAllResp> getVibrationSensorCodeList = getAcceleration(meters, sysDictionaries,req);
            //振动
            StatisticsMechanismVibrationResp vibration = mechanisms.stream().filter(mechanism -> mechanism.getPosition().equals(position.getValue())).findFirst().orElse(new StatisticsMechanismVibrationResp());
            //根据位置查询该位置的趋势平稳度
            List<StatisticsTrendstabilityResp> trend = trends.stream().filter(trendes -> trendes.getMonitorLocation().equals(position.getValue())).collect(Collectors.toList());
            //卷筒轴健康度
            HealthResp reelHealthData = reelHealtList.stream().filter(healthResp -> healthResp.getRemark().equals(position.getValue().toString()))
                    .max(Comparator.comparing(HealthResp::getTime))
                    .orElse(new HealthResp());
            //轴承健康度
            HealthResp bearingHealth = bearingHealtList.stream().filter(healthResp -> healthResp.getRemark().equals(position.getValue().toString()))
                    .max(Comparator.comparing(HealthResp::getTime))
                    .orElse(new HealthResp());

            List<String> evaluateObject = trend.stream().map(StatisticsTrendstabilityResp::getEvaluateObject)
                    .filter(object -> !healths.contains(object)).distinct().collect(Collectors.toList());
            for (String evaluate : evaluateObject) {
                StatisticTrendSmoothnessResp trendData = new StatisticTrendSmoothnessResp();
                StatisticsTrendstabilityResp latestSmoothness = trend.stream().filter(x -> x.getEvaluateObject().equals(evaluate)).max(Comparator.comparing(StatisticsTrendstabilityResp::getTime)).orElse(new StatisticsTrendstabilityResp());

                trendData.setEvaluateObject(latestSmoothness.getEvaluateObject());
                trendData.setStatusValue(Float.valueOf(String.format("%.2f",latestSmoothness.getStatusValue())));
                trendDatas.add(trendData);
            }
            data.setTrendStabilityTypeName(position.getName());
            data.setTrendStabilityType(position.getValue());
            data.setState(!CollectionUtils.isEmpty(getVibrationSensorCodeList));
            data.setInstitutionalVibration(vibration.getInstitutionalVibration());
            data.setVibrationSource(vibration.getVibrationSource());
            data.setBearingHealth(bearingHealth.getStatusValue() == null ? 0 : Float.parseFloat(String.format("%.2f",bearingHealth.getStatusValue())));
            data.setReelHealth(reelHealthData.getStatusValue() == null ? 0 : Float.parseFloat(String.format("%.2f",reelHealthData.getStatusValue())));
            data.setSmoothnessRequests(trendDatas);
            centerTrendStabilityResps.add(data);
        }
        return centerTrendStabilityResps;
    }


    public List<TDSensorCodeDataAllResp> getAcceleration(StressMetersReq meters, List<SysDictionaryResp> sysDictionaries,CenterTrendstabilityReq req) {
        List<TDSensorCodeDataAllResp> accelerationMetersResp = new ArrayList<>();
        for (String sensorCode : meters.getSensorCodeList()) {
            //查询主梁传感器数据
            StressMetersReq mete = new StressMetersReq();
            SysDictionaryResp dictionary = sysDictionaries.stream().filter(dictionaries -> dictionaries.getCode().equals(sensorCode)).findFirst().orElse(null);
            mete.setSensorCode(sensorCode);
            mete.setTableName(dictionary != null ? dictionary.getName() : null);
            mete.setStartTime(meters.getStartTime());
            mete.setEndDateTime(meters.getEndDateTime());
            mete.setEquipmentCode(req.getEquipmentCode());
            mete.setLimit(meters.getLimit());
            List<TDSensorCodeDataAllResp> accelerations = statisticStressMetersMapper.getStrainListA(mete).stream().sorted(Comparator.comparing(TDSensorCodeDataAllResp::getTs)).collect(Collectors.toList());
            accelerationMetersResp.addAll(accelerations);
        }
        return accelerationMetersResp;
    }


    //主梁平稳度
    public CommonResult<List<StatisticTrendSmoothnessResp>> getMainBeamTrendSmoothnessAsync(@RequestBody CenterTrendstabilityReq req) {
        if (StringUtils.isEmpty(req.getEquipmentCode())) {
            return CommonResult.failed("设备不存在");
        }
        List<StatisticTrendSmoothnessResp> statisticTrendSmoothnessResps = new ArrayList<>();
        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
        dictionaryReq.setParentCode(Constants.STATISTICS_TRENDSTABILITY_MONITOR_LOCATION);
        dictionaryReq.setRemark(Constants.MAIN_BEAM);
        dictionaryReq.setOperateObject(req.getEquipmentCode());
        dictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        //位置
        List<SysDictionaryResp> positionData = sysDictionaryMapper.getList(dictionaryReq);
        List<Integer> position = positionData.stream().map(SysDictionaryResp::getValue).collect(Collectors.toList());
        StrainSensorQueryReq sensorResp = new StrainSensorQueryReq();
        sensorResp.setEquipmentCode(req.getEquipmentCode());
        sensorResp.setMonitorLocations(position);
        sensorResp.setDateTime(req.getViewDate());
        //查询趋势平稳度
        List<StatisticsTrendstabilityResp> trends = statisticsTrendstabilityMapper.getTimeList(sensorResp);
        List<String> evaluateObject = trends.stream().
                map(StatisticsTrendstabilityResp::getEvaluateObject).distinct().collect(Collectors.toList());
        for (String evaluate : evaluateObject) {
            StatisticTrendSmoothnessResp data = new StatisticTrendSmoothnessResp();
            StatisticsTrendstabilityResp latestSmoothness = trends.stream().filter(x -> x.getEvaluateObject().equals(evaluate)).max(Comparator.comparing(StatisticsTrendstabilityResp::getTime)).orElse(new StatisticsTrendstabilityResp());
            data.setEvaluateObject(latestSmoothness.getEvaluateObject());
            data.setStatusValue(Float.valueOf(String.format("%.2f",latestSmoothness.getStatusValue())));
            statisticTrendSmoothnessResps.add(data);
        }
        return CommonResult.success(statisticTrendSmoothnessResps);
    }


    //主结构平稳度
    public CommonResult<List<StatisticTrendSmoothnessResp>> getMainStructureTrendSmoothnessAsync(@RequestBody CenterTrendstabilityReq req) {
        if(StringUtils.isEmpty(req.getEquipmentCode())){
            return CommonResult.failed("设备不存在");
        }
        List<StatisticTrendSmoothnessResp> statisticTrendSmoothnessResps = new ArrayList<>();
        SysDictionaryReq dictionary = new SysDictionaryReq();
        dictionary.setParentCode(Constants.STATISTICS_TRENDSTABILITY_MONITOR_LOCATION);
        dictionary.setRemark(Constants.MAIN_STRUCTURE);
        dictionary.setOperateObject(req.getEquipmentCode());
        dictionary.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        //位置
        List<SysDictionaryResp> positionData = sysDictionaryMapper.getList(dictionary);
        List<Integer> position = positionData.stream().map(SysDictionaryResp::getValue).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(position)) {
            return CommonResult.success(statisticTrendSmoothnessResps);
        }
        StrainSensorQueryReq sensorResp = new StrainSensorQueryReq();
        sensorResp.setEquipmentCode(req.getEquipmentCode());
        sensorResp.setMonitorLocations(position);
        sensorResp.setDateTime(req.getViewDate());
        //查询趋势平稳度
        List<StatisticsTrendstabilityResp> trends = statisticsTrendstabilityMapper.getTimeList(sensorResp);
        List<String> evaluateObject = trends.stream().
                map(StatisticsTrendstabilityResp::getEvaluateObject).distinct().collect(Collectors.toList());
        for (String evaluate : evaluateObject) {
            StatisticTrendSmoothnessResp statisticTrendSmoothnessResp = new StatisticTrendSmoothnessResp();
            StatisticsTrendstabilityResp latestSmoothness = trends.stream().filter(x -> x.getEvaluateObject().equals(evaluate)).max(Comparator.comparing(StatisticsTrendstabilityResp::getTime)).orElse(new StatisticsTrendstabilityResp());
            statisticTrendSmoothnessResp.setEvaluateObject(latestSmoothness.getEvaluateObject());
            statisticTrendSmoothnessResp.setStatusValue(Float.valueOf(String.format("%.2f",latestSmoothness.getStatusValue())));
            statisticTrendSmoothnessResps.add(statisticTrendSmoothnessResp);
        }
        return CommonResult.success(statisticTrendSmoothnessResps);
    }


    public SysDictionaryResp tdTableData(String code, String equipmentCode) {

        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.setParentCode(Constants.EQUIPMENT_CODE_TDSTABLE);
        sysDictionaryReq.setOperateObject(equipmentCode);
        sysDictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> dictionaryRespList = sysDictionaryMapper.getList(sysDictionaryReq);
        return dictionaryRespList.stream().filter(sysDictionaryResp -> sysDictionaryResp.getCode().contains(code)).findFirst().orElse(new SysDictionaryResp());
    }

    public List<SysDictionaryResp> getSysDictionaryResp(String parentCode, String operateObject) {

        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.setParentCode(parentCode);
        sysDictionaryReq.setOperateObject(operateObject);
        sysDictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        return sysDictionaryMapper.getList(sysDictionaryReq);
    }


    public StartEndTImeResp sensorStatistics(LocalDateTime ts, Integer statistics) {
        StartEndTImeResp startEndTImeResp = new StartEndTImeResp();
        //查询状态监控中心数量与区间
        SysDictionaryReq dict = new SysDictionaryReq();
        dict.setParentCode(Constants.SENSOR_STATISTICS);
        dict.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> datas = sysDictionaryMapper.getList(dict);
        SysDictionaryResp valueRange = datas.stream().filter(x -> x.getValue().equals(statistics)).findFirst().orElse(new SysDictionaryResp());
        //获取查询时间间隔（秒）
        int number = valueRange.getCode() != null ? Integer.parseInt(valueRange.getCode()) : Constants.TIME_DIFFERENCE;
        //获取查询数量
        int limit = valueRange.getName() != null ? Integer.parseInt(valueRange.getName()) : Constants.NUMBER_OF_QUERIES;

        //查询开始时间
        LocalDateTime startDate = ts.minusSeconds(number);
        //查询结束时间
        String endDate = ts.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        startEndTImeResp.setStartTime(startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        startEndTImeResp.setEndDateTime(endDate);
        startEndTImeResp.setLimit(limit);
        return startEndTImeResp;
    }

    public StartEndTImeResp timeRange(LocalDateTime ts, Integer timeRange) {
        StartEndTImeResp startEndTImeResp = new StartEndTImeResp();
        //查询状态监控中心历史区间
        SysDictionaryReq dict = new SysDictionaryReq();
        dict.setParentCode(Constants.CONDITION_MONITORING_HISTORY_INTERVAL);
        dict.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> datas = sysDictionaryMapper.getList(dict);
        //首页应变传感器查询数量与间隔
        SysDictionaryResp data = datas.stream().filter(x -> x.getValue().equals(timeRange)).findFirst().orElse(new SysDictionaryResp());
        startEndTImeResp.setStartTime(ts.toLocalDate() + " " + data.getCode());
        startEndTImeResp.setEndDateTime(ts.toLocalDate() + " " + data.getName());
        startEndTImeResp.setLimit(getTimeSpeed(startEndTImeResp.getStartTime(),startEndTImeResp.getEndDateTime()));
        return startEndTImeResp;
    }

    public List<SysDictionaryResp> getSysDictionaryRespHistoryInterval() {
        //查询状态监控中心历史区间
        SysDictionaryReq dict = new SysDictionaryReq();
        dict.setParentCode(Constants.CONDITION_MONITORING_HISTORY_INTERVAL);
        dict.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> datas = sysDictionaryMapper.getList(dict);
        for(SysDictionaryResp sysDictionaryResp:datas){
            sysDictionaryResp.setName(sysDictionaryResp.getCode()+"~"+sysDictionaryResp.getName());
        }
        return datas;
    }


    public Integer getTimeSpeed(String startTime, String endTime) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long eTime = 0;
        try {
            eTime = df.parse(endTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long sTime = 0;
        try {
            sTime = df.parse(startTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return Math.toIntExact((eTime - sTime) / 1000);
    }

    //根据value获取对应颜色
    public String colorCode(Integer value){
        SysDictionaryReq dict = new SysDictionaryReq();
        dict.setParentCode(Constants.SENSOR_COLOR);
        dict.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> datas = sysDictionaryMapper.getList(dict);
        return datas.stream().filter(x->x.getValue().equals(value)).findFirst().orElse(new SysDictionaryResp()).getCode();
    }
}
